﻿using AutoLoginHelper;
using System;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using static System.Collections.Specialized.BitVector32;
using Newtonsoft.Json;

namespace ConsoleApp
{
    class Program
    {
        // 配置路径
        //static string iniFilePath = "E:\\code\\VS2022\\CSharp\\test.ini";
        static string iniFileName = "config.ini";
        // user区域
        static string section = "user";
        static string usernameKey = "username";
        static string usernameDefaultValue = "user01";


        static string passwordKey = "password";
        static string passwordDefaultValue = "password";


        static string schoolWebURL = "http://172.16.3.200";

        static async Task Main(string[] args)
        {
            IntPtr handle = GetConsoleWindow(); // 获取控制台窗口句柄
            ShowWindow(handle, SW_HIDE); // 隐藏控制台窗口

            using (HttpClient client = new HttpClient())
            {
                try
                {

                    client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0");  // 设置用户代理信息
                    client.DefaultRequestHeaders.Add("Host", "172.16.3.200");  
                    client.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7");

                    HttpResponseMessage response = await client.GetAsync(schoolWebURL);

                    response.EnsureSuccessStatusCode();

                    // 指定编码方式为 GB2312
                    Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                    Encoding encoding = Encoding.GetEncoding("GB2312");

                    byte[] responseBytes = await response.Content.ReadAsByteArrayAsync();
                    string responseBody = encoding.GetString(responseBytes);

                    string pattern = @"<title>(.*?)</title>";
                    Match match = Regex.Match(responseBody, pattern);

                    if (match.Success)
                    {
                        string title = match.Groups[1].Value;
                        Console.WriteLine($"页面标题: {title}");


                        // 如果是注销页，则不用管
                        if ("注销页".Equals(title))
                        {
                            Console.WriteLine("已经登录，无需登录");
                        }
                        else
                        {
                            // 如果没有登录，则登录
                            Console.WriteLine("没有登录，正在登录");


                            // 先检查配置文件
                            string tempDIrPath = Path.GetTempPath();  // 获取系统临时目录路径
                            string iniFilePath = Path.Combine(tempDIrPath, iniFileName);  // 目标文件路径

                            Console.WriteLine(iniFilePath);

                            if (!File.Exists(iniFilePath))
                            {
                                Console.WriteLine("配置文件不存在");

                                // 运行完代码后，调用Exit方法退出程序
                                Environment.Exit(0);
                                return;
                            }



                            string usernameValue = OperateIniFile.ReadIniData(section, usernameKey, usernameDefaultValue, iniFilePath);
                            string passwordValue = OperateIniFile.ReadIniData(section, passwordKey, passwordDefaultValue, iniFilePath);


                            string schoolWebLoginURLFormatStr = "http://172.16.3.200/drcom/login?callback=dr1003&DDDDD={0}&upass={1}&0MKKey=123456&R1=0&R2=&R3=0&R6=0&para=00&v6ip=&terminal_type=1&lang=zh-cn&jsVersion=4.1.3&v=3277&lang=zh";

                            string schoolWebLoginURL = string.Format(schoolWebLoginURLFormatStr, usernameValue, passwordValue);
                        
                            HttpResponseMessage loginResponse=await client.GetAsync(schoolWebLoginURL);

                            byte[] lgoinResponseBytes = await loginResponse.Content.ReadAsByteArrayAsync();
                            string loginResponseBody = encoding.GetString(lgoinResponseBytes).Trim();

                            // 将 JSON 字符串反序列化为自定义对象
                            MyDataModel obj = JsonConvert.DeserializeObject<MyDataModel>(loginResponseBody.Substring(7,loginResponseBody.Length-8));

                            //Match titleMatch = Regex.Match(loginResponseBody, pattern);
                            //string newTitle = match.Groups[1].Value;

                            if (obj.result==1)
                            {
                                Console.WriteLine("登录成功了！");
                            }
                            else
                            {
                                Console.WriteLine("登录失败。可能原因：1、未连接校园网。2、可能账号密码错误。");
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("网络出错");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"dAn error occurre: {ex.Message}");
                }
            }

            // 运行完代码后，调用Exit方法退出程序
            Environment.Exit(0);
        }

        // 导入Windows API函数
        [System.Runtime.InteropServices.DllImport("kernel32.dll")]
        private static extern IntPtr GetConsoleWindow();

        [System.Runtime.InteropServices.DllImport("user32.dll")]
        private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        private const int SW_HIDE = 0;

    }


    public class MyDataModel
    {
        // 结果
        // 1表示登录成功
        // 0表示登录失败
        public int result { get; set; }
    }
}